﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace CustomFieldTypes
{
    public class TableCheckFieldValue
    {
        public const char InterValueDelimiter = ',';
        public const char InterPropertyDelimiter = '|';

        public string Name = string.Empty;
        public bool Checked = false;
        public string Login = string.Empty;
        public string UserName { get; set; }

        public override string ToString()
        {
            return string.Concat(
                this.Name.Trim(), InterPropertyDelimiter,
                this.Checked, InterPropertyDelimiter,
                this.Login.Trim(), InterPropertyDelimiter,
                this.UserName.Trim());
        }

        public static List<TableCheckFieldValue> FromFieldValue(string fieldValue)
        {
            var allValues = new List<TableCheckFieldValue>();
            var splittedValues = fieldValue.Split(new char[] { InterValueDelimiter }, StringSplitOptions.RemoveEmptyEntries);

            foreach (string val in splittedValues)
            {
                var valueVals = val.Split(new char[] { InterPropertyDelimiter }, StringSplitOptions.RemoveEmptyEntries);
                allValues.Add(new TableCheckFieldValue
                {
                    Name = valueVals.Length > 0 ? valueVals[0].Trim() : string.Empty,
                    Checked = valueVals.Length > 1 && !string.IsNullOrEmpty(valueVals[1]) ?
                        bool.Parse(valueVals[1]) : false,
                    Login = valueVals.Length > 2 ? valueVals[2].Trim() : string.Empty,
                    UserName = valueVals.Length > 3 ? valueVals[3].Trim() : string.Empty
                });
            }

            return allValues;
        }

        public static string ToFieldValue(List<TableCheckFieldValue> listOfValues)
        {
            return string.Concat(
                (from value in listOfValues
                 select value.ToString() + InterValueDelimiter).ToArray());
        }
    }
}
